﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HdcSimulation.Resource
{
    /// <summary>
    /// 高精度定时器类，提供类似DispatcherTimer的接口类型，精度可达到1ms
    /// </summary>
    public class HighPrecisionTimer
    {
        private Stopwatch _stopwatch;
        private long _intervalTicks;
        private bool _isRunning;
        private Action<object> _tickHandler;
        private object _state;
        private bool _isRepeating;

        /// <summary>
        /// 初始化HighPrecisionTimer类的新实例
        /// </summary>
        /// <param name="interval">定时器间隔时间</param>
        /// <param name="tickHandler">定时器触发时执行的回调方法</param>
        /// <param name="state">传递给回调方法的状态对象</param>
        public HighPrecisionTimer(TimeSpan interval, Action<object> tickHandler, object state)
        {
            if (interval < TimeSpan.FromMilliseconds(1))
            {
                throw new ArgumentException("间隔时间必须大于等于1毫秒", nameof(interval));
            }

            if (tickHandler == null)
            {
                throw new ArgumentNullException(nameof(tickHandler));
            }

            _stopwatch = new Stopwatch();
            _intervalTicks = interval.Ticks;
            _tickHandler = tickHandler;
            _state = state;
            _isRepeating = false;
            _isRunning = false;
        }

        /// <summary>
        /// 获取或设置定时器的间隔时间
        /// </summary>
        public TimeSpan Interval
        {
            get { return new TimeSpan(_intervalTicks); }
            set
            {
                if (value < TimeSpan.FromMilliseconds(1))
                {
                    throw new ArgumentException("间隔时间必须大于等于1毫秒", nameof(value));
                }
                _intervalTicks = value.Ticks;
            }
        }

        /// <summary>
        /// 获取一个值，指示定时器是否正在运行
        /// </summary>
        public bool IsRunning => _isRunning;

        /// <summary>
        /// 获取一个值，指示定时器是否是重复执行
        /// </summary>
        public bool IsRepeating => _isRepeating;

        /// <summary>
        /// 开始定时器
        /// </summary>
        public void Start()
        {
            if (_isRunning)
                return;

            _stopwatch.Reset();
            _stopwatch.Start();
            _isRunning = true;
            _isRepeating = false;
            ProcessTimer();
        }

        /// <summary>
        /// 开始重复执行的定时器
        /// </summary>
        public void StartRepeating()
        {
            if (_isRunning)
                return;

            _stopwatch.Reset();
            _stopwatch.Start();
            _isRunning = true;
            _isRepeating = true;
            ProcessTimer();
        }

        /// <summary>
        /// 停止定时器
        /// </summary>
        public void Stop()
        {
            _stopwatch.Stop();
            _isRunning = false;
        }

        /// <summary>
        /// 手动触发一次定时器操作
        /// </summary>
        public void Tick()
        {
            _tickHandler?.Invoke(_state);
        }

        /// <summary>
        /// 处理定时器逻辑
        /// </summary>
        private void ProcessTimer()
        {
            // 在单独的线程中运行定时器逻辑
            var thread = new Thread(() =>
            {
                while (_isRunning)
                {
                    if (_stopwatch.IsRunning && _stopwatch.ElapsedTicks >= _intervalTicks)
                    {
                        Tick();

                        if (!_isRepeating)
                        {
                            _stopwatch.Stop();
                            _isRunning = false;
                        }
                        else
                        {
                            _stopwatch.Reset();
                            _stopwatch.Start();
                        }
                    }

                    // 短暂休眠以避免过度占用CPU资源
                    Thread.Sleep(1);
                }
            });

            thread.IsBackground = true;
            thread.Start();
        }
    }
}
